package main

import (
	"fmt"
	"net"
	"os"
	// "time"
)

const bufferSize = 2048

// GOOS=linux GOARCH=amd64 go build -o udp_server udp_server.go
// GOOS=windows GOARCH=amd64 go build -o udp_server.exe udp_server.go
func main() {
	defer func(){ fmt.Scanln()}()
	fmt.Println("=== udp server tool (v1.0.0) ===")

	var serverPort string;
	if len(os.Args) == 2 {
		serverPort = os.Args[1]
	}else{
		fmt.Println("Example:",  "udp_server 5002")
		fmt.Println()
		fmt.Println("Please enter the listening port:")
		fmt.Scanf("%s",&serverPort)

		if serverPort == "" {
			fmt.Println("=> ServerPort error")
			return 
		}
	}

	serverAddr, err := net.ResolveUDPAddr("udp", ":"+serverPort)
	if err != nil {
		fmt.Println("=> ResolveUDPAddr failed:", err)
		return
	}

	sockFd, err := net.ListenUDP("udp", serverAddr)
	if err != nil {
		fmt.Println("=> UDP socket creation failed:", err)
		return
	}
	defer sockFd.Close()

	fmt.Printf("UDP server listening on port %s...\n", serverPort)
	buffer := make([]byte, bufferSize)

	for {
		n, clientAddr, err := sockFd.ReadFromUDP(buffer)
		if err != nil {
			fmt.Println("=> Receive message failed:", err)
			continue
		}
		clientIP := clientAddr.IP.String()
		clientPort := clientAddr.Port
		fmt.Printf("Received (%s:%d): %s\n", clientIP, clientPort, string(buffer[:n]))


		// time.Sleep(3*time.Second)
		response := fmt.Sprintf("Hello %s",string(buffer[:n]))// "Pong"+ string(buffer[:n])
		_, err = sockFd.WriteToUDP([]byte(response), clientAddr)
		if err != nil {
			fmt.Println("=> Send message failed:", err)
			continue
		}
	}
}
